#!/bin/bash

# 定义变量
GITEE_REPO_URL="git@gitee.com:jifakeji_0/dy-zsj.git"
GIT_CLONE_DIR="/opt/zsj/code/dy-zsj"
BUILD_DIR="${GIT_CLONE_DIR}/target"
JAR_FILE="dy-zsj.jar"
REMOTE_SERVER_DIR="/opt/zsj/tmp"

REMOTE_SERVERS=(
    "root@123.57.7.121:/opt/zsj/tmp"
    "root@172.16.0.211:/opt/zsj/tmp"
)

echo "删除项目..."
rm -rf $GIT_CLONE_DIR

echo "克隆项目..."
git clone $GITEE_REPO_URL $GIT_CLONE_DIR

cd $GIT_CLONE_DIR

echo "编译并打包项目..."
mvn clean package

if [ -f "$BUILD_DIR/$JAR_FILE" ]; then
    echo "jar包生成成功！"
else
    echo "jar包生成失败！"
    exit 1
fi

echo "将jar包复制到远程服务器..."
for REMOTE_SERVER in "${REMOTE_SERVERS[@]}"; do
    REMOTE_USER=$(echo $REMOTE_SERVER | cut -d'@' -f1)
    REMOTE_IP_DIR=$(echo $REMOTE_SERVER | cut -d'@' -f2)
    REMOTE_IP=$(echo $REMOTE_IP_DIR | cut -d':' -f1)
    REMOTE_DIR=$(echo $REMOTE_IP_DIR | cut -d':' -f2)

    echo "将jar包复制到服务器 $REMOTE_USER@$REMOTE_IP 的 $REMOTE_DIR 目录..."
    scp "$BUILD_DIR/$JAR_FILE" "$REMOTE_USER@$REMOTE_IP:$REMOTE_DIR"

    # 检查是否复制成功
    if ! ssh "$REMOTE_USER@$REMOTE_IP" "test -f $REMOTE_DIR/$JAR_FILE"; then
        echo "jar包复制到服务器 $REMOTE_USER@$REMOTE_IP 失败！"
        exit 1
    fi
done

echo "将jar包复制到自己服务器目录..."
cp $BUILD_DIR/$JAR_FILE $REMOTE_SERVER_DIR
if [ -f "$REMOTE_SERVER_DIR/$JAR_FILE" ]; then
    echo "jar包复制成功！"
else
    echo "jar包复制失败！"
    exit 1
fi

echo "所有操作完成！"
